package com.beidasoft.flip.webframe.core.jpa;

import javax.persistence.EntityManager;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import com.beidasoft.flip.webframe.core.pojo.DO;

/**
 * @author 肖翔
 * @version 1.0
 * @date 2019/12/04
 * @email winner_xiaoxiang@163.com
 * @since 1.0
 */
public class FlipJpaRepositoryFactoryBean<T extends JpaRepository<S, ID>, S, ID>
    extends JpaRepositoryFactoryBean<T, S, ID> {

    /**
     * @param repositoryInterface
     */
    public FlipJpaRepositoryFactoryBean(Class<? extends T> repositoryInterface) {
        super(repositoryInterface);

    }

    /**
     * <p>重写该方法，用当前的自定义的FlipJpaRepositoryFactory类创建实例</p>
     */
    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
        return new FlipJpaRepositoryFactory<DO, ID>(entityManager);
    }

    /**
     * <p>私有化静态工厂</p>
     * @author 肖翔
     * @version 1.0
     * @date 2019/12/04
     * @email winner_xiaoxiang@163.com
     * @since 1.0
     */
    private static class FlipJpaRepositoryFactory<T extends DO, ID> extends JpaRepositoryFactory {

        /**
         * @param entityManager
         */
        public FlipJpaRepositoryFactory(EntityManager entityManager) {
            super(entityManager);
        }

        /**
         * <p>重写实现的方法，用于覆盖超类的方法，返回自定义的FlipJpaRepositoryImpl的对象</p>
         */
        @SuppressWarnings("unchecked")
        @Override
        protected JpaRepositoryImplementation<?, ?> getTargetRepository(RepositoryInformation information,
            EntityManager entityManager) {
            return new FlipJpaRepositoryImpl<T, ID>((Class<T>)information.getDomainType(), entityManager);
        }

        /**
         * <p>获取当前自定义类的类型</p>
         */
        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return FlipJpaRepositoryImpl.class;
        }
    }

}
